const { sqlite3 } = require('../../mysql')

// 获取文章数据
const getPosts = async (ctx) => {
  const data = await sqlite3('posts').where({
    post_status: 'publish',
    ping_status: 'open'
  }).orderBy('id', 'desc').select()
  if (data) {
    ctx.body = {
      data,
      result: true,
    }
  } else {
    ctx.body = {
      result: false,
    }
  }
}

// 管理平台获取文章数据
const getInfoPosts = async (ctx) => {
  // console.log('ctx.query:', ctx.query)
  let formData = ctx.query
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.query
  let limitdata = {}
  let data = {}
  if (keyword) {
    // console.log('query:', keyword)
    limitdata = await sqlite3('posts').select()
    data = await sqlite3('posts').where('id', 'LIKE', '%' + keyword + '%')
      .orderBy('id', 'desc').select().limit(formData.limit).offset(offset)
  } else {
    limitdata = await sqlite3('posts').select()
    data = await sqlite3('posts').orderBy('id', 'desc')
      .select().limit(formData.limit).offset(offset)
  }
  if (data) {
    // console.log(data)
    data.post_status = data.post_status === 'publish' ?1:0
    data.ping_status = data.ping_status === 'open' ?1:0
    ctx.body = {
      code: 200,
      item: data,
      total: limitdata.length,
      result: true
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台添加文章数据
const infoAdd = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  // let formData = ctx.request.body
  // const data = await sqlite3('posts').insert(
  //   formData
  // )
  // console.log(data)
  // if (data) {
  //   ctx.body = {
  //     code: 200,
  //     data: "success"
  //   }
  // } else {
  //   ctx.body = {
  //     code: false
  //   }
  // }
}

// 管理平台更新文章数据
const infoUpdate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('posts')
    .where('ID', formData.ID)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

const infoDelete = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('posts')
    .where('ID', formData.ID)
    .update('post_status', 'trash')
  console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

module.exports = { getPosts, getInfoPosts, infoAdd, infoUpdate, infoDelete }
